<!--
  * @Author: 郝奔 1425466221@qq.com
  * @Date: 2024-07-09 09:51:05
 * @LastEditors: gaoyu gy15354315043@163.com
 * @LastEditTime: 2024-11-15 13:59:08
  * @FilePath: \weshyper_dev_vue2\src\framework\unified-navigation\views\components\menu-search\views\index.vue
  * @Description: 
  * Copyright (c) 2024-present HBIS Digital Technology Co.,Ltd. All rights reserved. 
-->
<template>
  <div ref="searchBox" class="search-box">
    <div class="search-label" @click="onClickSearchLabel">
      <el-icon :size="16">
        <Search />
      </el-icon>
      <span class="text-label">
        搜索
      </span>

      <DtSvgIcon v-if="isMac" icon-class="search-command" />
      <DtSvgIcon v-else icon-class="search-ctrl" />

      <DtSvgIcon icon-class="search-k" />
    </div>

    <ContentDialog v-if="contenVisible" ref="contentDialog" @close="contenVisible = false" />
  </div>
</template>

<script lang="ts" setup>
import ContentDialog from './components/content-dialog.vue'
import { icons } from '@hbisdt-design/icons-vue'

const {Search} = icons

const contentDialog = ref()
const searchBox = ref()
const state = reactive({
  contenVisible: false, // 搜索框显示状态
})
const { contenVisible } = toRefs(state)
const isMac = ref(false)
isMac.value = navigator.userAgent.toLowerCase().indexOf("mac") > 0 && navigator.userAgent.toLowerCase().indexOf("os") > 0 
onMounted(()=>{
  document.addEventListener('keydown', handleKeyEvent)
})
/*
 * @param event 键盘事件对象
 * @returns 无返回值
 */
const  handleKeyEvent=(event:KeyboardEvent):void=>{
      if (isMac.value) {
        // 苹果系统下执行的操作
        if(event.metaKey && event.key == 'k'){
          onClickSearchLabel()
        }
      } else {
        // windows系统下执行的操作
        if(event.ctrlKey && event.key == 'k'){
          onClickSearchLabel()
          event.preventDefault()
        }
      }
    }
/**
 * 把模态框添加到 body
 */
const appendToBody = (): void => {
  document.body.appendChild(contentDialog.value.$el)
}

const onClickSearchLabel = (): void => {
  contenVisible.value = true
  nextTick(() => {
    appendToBody()
  })
}
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyEvent)
})
</script>

<style lang="scss" scoped>
.search-box {
  width: 138px;
  height: 34px;
  position: relative;
  cursor: pointer;

  .search-label {
    width: 100%;
    height: 100%;
    border-radius: 19px;
    display: flex;
    flex-direction: row;
    justify-content: space-evenly;
    align-items: center;
    padding: 6px 8px;
    font-size: 14px;

    &:hover {
      border: 1px solid #004FFF;
    }

    .text-label {
      margin-right: 5px;
      margin-left: 5px;
      position: relative;
      top: -1px;
    }

    .el-icon-search {
      font-size: 20px;
    }

    .svg-icon {
      font-size: 28px;
    }
  }
}
</style>